package com.zprmb.udzt;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.view.RoundImageView;
import com.zprmb.udzt.view.SystemBarTintManager;

/**
 * 个人中心s
 * 
 * @author shenshao
 */
public class AccountActivity extends BaseActivity implements OnClickListener,
		OnRefreshListener2<ScrollView> {
	private RelativeLayout rl_real_name, rl_my_qr, rl_pw_manger, rl_my_card,
			rl_more, rl_my_address, rl_idcard, rl_my_qq;
	private TextView tv_user_phone, tv_invite_code, tv_name_status,
			tv_real_name, tv_idcard, tv_my_qq, tv_address_status, tv_unread,
			test_status;
	
	private ImageView img_user, right1, right2, img_pr;
	private View real_name_line;
	private Button btn_signout;
	private Boolean paypass;
	private TextView tv_bank_card;
	private int first = 1;
	private RelativeLayout rl_my_test;
	private LinearLayout li_unread;
	private RoundImageView view;
	private ImageView img_nowork;
	private PullToRefreshScrollView sv;
	private boolean login;
	private RelativeLayout rl_help_center;
	private TextView tv_version;
	private String my_status;
	private ImageView img_back, img_message;

	private String investcode;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_center);
		BbtApplication.getInstance().addActvity(this);
		setImmersionStatus();

		rl_real_name = (RelativeLayout) findViewById(R.id.rl_real_name);
		rl_my_qq = (RelativeLayout) findViewById(R.id.rl_my_oicq);
		sv = (PullToRefreshScrollView) findViewById(R.id.sv);
		rl_my_qr = (RelativeLayout) findViewById(R.id.rl_my_qr);
		li_unread = (LinearLayout) findViewById(R.id.li_unread);
		tv_unread = (TextView) findViewById(R.id.tv_unread);
		view = (RoundImageView) findViewById(R.id.user_img);
		img_back = (ImageView) findViewById(R.id.img_back);
		img_pr = (ImageView) findViewById(R.id.img_pr);
		tv_version = (TextView) findViewById(R.id.tv_version);
		right1 = (ImageView) findViewById(R.id.right1);
		tv_bank_card = (TextView) findViewById(R.id.tv_bank_card);
		right2 = (ImageView) findViewById(R.id.right2);
		img_message = (ImageView) findViewById(R.id.img_unread);
		img_nowork = (ImageView) findViewById(R.id.iv_v4_nonetwork);
		rl_idcard = (RelativeLayout) findViewById(R.id.rl_idcard);
		rl_pw_manger = (RelativeLayout) findViewById(R.id.rl_pw_manger);
		rl_my_address = (RelativeLayout) findViewById(R.id.rl_my_address);
		rl_my_card = (RelativeLayout) findViewById(R.id.rl_my_card);
		rl_more = (RelativeLayout) findViewById(R.id.rl_more);
		tv_user_phone = (TextView) findViewById(R.id.user_phone);
		rl_help_center = (RelativeLayout) findViewById(R.id.rl_help_center);
		tv_invite_code = (TextView) findViewById(R.id.my_invite_code);
		tv_name_status = (TextView) findViewById(R.id.name_status);
		real_name_line = (View) findViewById(R.id.real_name_line);
		tv_real_name = (TextView) findViewById(R.id.tv_real_name);
		btn_signout = (Button) findViewById(R.id.btn_signout);
		tv_idcard = (TextView) findViewById(R.id.tv_card_id);
		tv_my_qq = (TextView) findViewById(R.id.my_qq);
		rl_my_test = (RelativeLayout) findViewById(R.id.rl_my_test);
		test_status = (TextView) findViewById(R.id.test_status);
		tv_address_status = (TextView) findViewById(R.id.address_status);
		img_pr.setOnClickListener(this);
		li_unread.setOnClickListener(this);
		rl_my_card.setOnClickListener(this);
		btn_signout.setOnClickListener(this);
		rl_help_center.setOnClickListener(this);
		rl_my_qr.setOnClickListener(this);
		rl_my_qq.setOnClickListener(this);
		rl_my_test.setOnClickListener(this);
		rl_pw_manger.setOnClickListener(this);
		rl_real_name.setOnClickListener(this);
		rl_more.setOnClickListener(this);
		sv.setOnRefreshListener(this);
		rl_my_address.setOnClickListener(this);
		view.setOnClickListener(this);
		sv.setVisibility(View.GONE);
		img_nowork.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				initData(true);
			}
		});

		initData(true);
	}

	public void getBitmap(final String url) {

		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();

				try {
					Bitmap bm = null;

					URL iconUrl = new URL(url);
					URLConnection conn = iconUrl.openConnection();
					HttpURLConnection http = (HttpURLConnection) conn;

					int length = http.getContentLength();

					conn.connect();
					// 获得图像的字符流
					InputStream is = conn.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(is,
							length);
					bm = BitmapFactory.decodeStream(bis);
					Message message = new Message();
					message.obj = bm;
					message.what = 0;
					handler.sendMessage(message);

					bis.close();
					is.close();// 关闭流

				} catch (Exception e) {
					e.printStackTrace();
					Log.e("转换异常", e.toString());
				}
			}
		}.start();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}

	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initData(false);

	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			if (msg.what == 1) {
				initData(true);
			} else {

				view.setImageBitmap((Bitmap) msg.obj);

			}
			sv.onRefreshComplete();

		};
	};

	private void initData(boolean ishow) {
		// TODO Auto-generated method stub

		VolleryUtil volleryUtil = new VolleryUtil() {

			@SuppressWarnings("unused")
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				LogUtils.e("个人", jsonObject.toString());

				if (jsonObject.optInt("success") == 1) {
					sv.setVisibility(View.VISIBLE);
					img_nowork.setVisibility(View.GONE);
					JSONObject json1 = jsonObject.optJSONObject("data");
					JSONObject json2 = json1.optJSONObject("riskData");
					paypass = json1.optBoolean("payPass");
					tv_version.setText("当前版本" + getAppVersion());

					login = true;
					if (json1.optString("headPicture").equals("null")) {
						if (json1.optString("sex").equals("男")) {
							view.setImageResource(R.drawable.img_boy);

						} else {
							view.setImageResource(R.drawable.img_girl);
						}

					} else {

						getBitmap(json1.optString("headPicture"));
					}
					if (json1.optBoolean("isBindCard")) {
						tv_bank_card.setVisibility(View.GONE);
					} else {
						tv_bank_card.setVisibility(View.VISIBLE);
					}
					if (json1.optBoolean("nameAuth")) {
						rl_idcard.setVisibility(View.VISIBLE);
						real_name_line.setVisibility(View.VISIBLE);
						tv_name_status.setText("姓名");
						right1.setVisibility(View.GONE);
						right2.setVisibility(View.GONE);
						tv_real_name.setText(json1.optString("userName"));
						tv_idcard.setText(json1.optString("idNumber"));
						String name = json1.optString("userName").substring(0,
								1);
						if (json1.optString("sex").equals("男")) {
							tv_user_phone.setText("您好，" + name + "先生!");

						} else {
							tv_user_phone.setText("您好，" + name + "女士!");
						}
					} else {
						tv_user_phone.setText(json1.optString("userMobile"));
					}
					if (json1.optString("qq").equals("null")) {
						tv_my_qq.setText("未设置");
					} else {
						tv_my_qq.setText(json1.optString("qq"));
					}

					if (json1.optString("addressList").equals("[]")) {
						tv_address_status.setVisibility(View.VISIBLE);
					} else {
						tv_address_status.setVisibility(View.INVISIBLE);
					}

					tv_invite_code
							.setText("邀请码:" + json1.optString("userCode"));
					investcode = json1.optString("userCode");

					if (json1.optInt("unreadRecords") == 0) {
						tv_unread.setVisibility(View.GONE);
					} else {
						if (json1.optInt("unreadRecords") > 99) {
							tv_unread.setText("..");
						} else {
							tv_unread.setText(json1.optString("unreadRecords"));
						}
						tv_unread.setVisibility(View.VISIBLE);
					}
				} else {

					if (jsonObject.optString("comment").equals("please login")) {
						tv_user_phone.setText("未登录");
						login = false;
						if (getShare().getInt("top", 0) == 1) {
							Editor editor = getShare().edit();
							editor.putInt("top", 0);
							editor.commit();
						} else {
							if (jsonObject.optString("comment").equals(
									"please login")) {
								Intent intent = new Intent(
										AccountActivity.this,
										LoginActivity.class);
								intent.putExtra("close", 1);
								startActivity(intent);
							} else {
								ToastUtil.showCenterToast(AccountActivity.this,
										jsonObject.optString("comment"));
							}
						}
					} else {
						Toast.makeText(AccountActivity.this,
								jsonObject.optString("comment"), 2000).show();
						AccountActivity.this.finish();
					}
				}

			}

			@Override
			public void onError() {
				// TODO Auto-generated method stub
				Toast.makeText(AccountActivity.this, "请求失败   请检查网络设置", 2000)
						.show();
				sv.setVisibility(View.GONE);
				img_nowork.setVisibility(View.VISIBLE);

			}
		};
		volleryUtil.setRequestMethod(0);
		volleryUtil.setShow(ishow);
		volleryUtil.setHeaders("token", getToken());
		volleryUtil.execute(AccountActivity.this, Constant.URL
				+ "/api/v5/user/accountCenter", "");
		// volleryUtil.execute(AccountActivity.this,
		// Constant.URL+"/api/v2/queryFunds?pageNo=10&pageSize=1&type=ALL", "");

	}

	public String saveBitmap(Bitmap bm) {
		File f = new File(getCacheDir(), "wd_phto.jpg");
		Log.e("地址", f.getPath());
		FileOutputStream out = null;
		if (f.exists()) {
			f.delete();
		}

		try {
			f.createNewFile();
			out = new FileOutputStream(f);
			bm.compress(Bitmap.CompressFormat.PNG, 50, out);
			upload(f);

		} catch (FileNotFoundException e) {
			Log.e("异常", e.getMessage() + "");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("异常", e.getMessage() + "");
			e.printStackTrace();
		} finally {
			try {
				out.close();
				bm.recycle();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return f.getPath();

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, data);
		if (data != null) {
			// 取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
			Uri mImageCaptureUri = data.getData();
			// 返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
			if (mImageCaptureUri != null) {
				Bitmap image;
				try {
					// 这个方法是根据Uri获取Bitmap图片的静态方法
					image = MediaStore.Images.Media.getBitmap(
							this.getContentResolver(), mImageCaptureUri);
					if (image != null) {
						view.setImageBitmap(image);

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Bundle extras = data.getExtras();
				if (extras != null) {
					// 这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
					Bitmap image = extras.getParcelable("data");
					if (image != null) {
						view.setImageBitmap(image);
						saveBitmap(image);

					}
				}
			}

		}
	}

	private void upload(File filename) {

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.rl_real_name:
			if (!login) {
				Toast.makeText(AccountActivity.this, "请先登录", 2000).show();
				return;
			}
			if (tv_name_status.getText().toString().equals("姓名")) {
				return;
			}

			Intent intent = new Intent(AccountActivity.this, RealName.class);
			startActivity(intent);

			break;
		case R.id.rl_my_qr:
			// if(!login){
			// Toast.makeText(AccountActivity.this, "请先登录", 2000).show();
			// return;
			// }
			// Intent intent2=new Intent(AccountActivity.this,My_QR.class);
			// intent2.putExtra("ref", investcode);
			// startActivity(intent2);
			break;
		case R.id.rl_pw_manger:
			if (!login) {
				Toast.makeText(AccountActivity.this, "请先登录", 2000).show();
				return;
			}
			Intent intent3 = new Intent(AccountActivity.this,
					Password_Manger.class);
			intent3.putExtra("pay", paypass);
			startActivity(intent3);
			break;
		case R.id.rl_my_card:
			if (!login) {
				Toast.makeText(AccountActivity.this, "请先登录", 2000).show();
				return;
			}
			Intent intent4 = new Intent(AccountActivity.this, MyBankCard.class);

			startActivity(intent4);
			break;
		case R.id.rl_more:
			Intent intent5 = new Intent(AccountActivity.this, More.class);
			startActivity(intent5);
			break;
		case R.id.rl_my_address:
			if (!login) {
				Toast.makeText(AccountActivity.this, "请先登录", 2000).show();
				return;
			}
			Intent intent6 = new Intent(AccountActivity.this, My_address.class);
			startActivity(intent6);
			break;
		case R.id.btn_signout:
			if (!login) {
				Toast.makeText(AccountActivity.this, "您还未登陆", 2000).show();
				return;
			}
			SharedPreferences sharedPreferences = getSharedPreferences(
					"config", MODE_PRIVATE);
			Editor ed = sharedPreferences.edit();
			ed.putString("token", "");
			// ed.putString("mobile", "");
			// ed.putString("usercode", "");
			ed.commit();
			// MainActivity.newInstance().setCurrentTabByTag("tab_tag_shouye");
			// Intent intent9=new
			// Intent(AccountActivity.this,MainActivity.class);
			// intent9.putExtra("who", 2);
			// startActivity(intent9);
			MainActivity.newInstance().setCurrentTabByTag("tab_tag_shouye");
			// AccountActivity.this.finish();
			break;
		case R.id.rl_my_oicq:
			if (!login) {
				Toast.makeText(AccountActivity.this, "请先登录", 2000).show();
				return;
			}
			if (tv_my_qq.getText().toString().equals("未设置")) {
				Intent intent7 = new Intent(AccountActivity.this,
						Update_My_QQ.class);
				intent7.putExtra("where", "2");
				startActivity(intent7);

			} else {
				Intent intent7 = new Intent(AccountActivity.this, MyOicq.class);
				intent7.putExtra("qq", tv_my_qq.getText().toString());
				startActivity(intent7);
			}
			break;
		case R.id.rl_help_center:
			Intent intente = new Intent(AccountActivity.this,
					V4WebViewActivity.class);
			intente.putExtra("url", "/h5/help?app=true");
			intente.putExtra("title", "帮助中心");
			startActivity(intente);
			break;

		case R.id.img_back:
			finish();
			break;
		case R.id.li_unread:
			Intent intent7 = new Intent(AccountActivity.this,
					V4WebViewActivity.class);
			// intent2.putExtra("url", "/h5/safety?app=true");

			intent7.putExtra("url", "/h5/messageCenter?app=true");

			intent7.putExtra("title", "我的消息");
			startActivity(intent7);
			break;
		case R.id.user_img:
			Intent intent8 = new Intent(AccountActivity.this,
					SelectImageActivity.class);
			// intent2.putExtra("url", "/h5/safety?app=true");

			startActivityForResult(intent8, 1);
			break;
		case R.id.rl_my_test:
			BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);

			break;
		case R.id.img_pr:
			if (!login) {
				Toast.makeText(AccountActivity.this, "请先登录", 2000).show();
				return;
			}
			Intent intent2 = new Intent(AccountActivity.this, My_QR.class);
			intent2.putExtra("ref", investcode);
			startActivity(intent2);
			break;

		}

	}

	private void setImmersionStatus() {
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			// 透明状态栏
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
	}

	public static void initSystemBar(Activity activity) {
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			setTranslucentStatus(activity, true);
		}
		SystemBarTintManager tintManager = new SystemBarTintManager(activity);
		tintManager.setStatusBarTintEnabled(true);
		// 使用颜色资源
		// tintManager.setNavigationBarTintResource(R.color.hongse);
		// tintManager.setTintColor(activity.getResources().getColor(R.color.huangse));
		// tintManager.setStatusBarTintResource(R.color.black);
	}

	@TargetApi(19)
	private static void setTranslucentStatus(Activity activity, boolean on) {
		Window win = activity.getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
		// TODO Auto-generated method stub
		handler.sendEmptyMessage(1);
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
		// TODO Auto-generated method stub

	}

}
